package org.ithasu.tools;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

public class ImageTools {

	public static final String[] FORMATS = { "png", "jpg" };

	private ImageTools() {
	}

	// -- Webcam ----------------------------------------

	public static BufferedImage getWebcamImage() {
		try {
			String tmpFile = IOTools.getTmpFolder() + "/webcam.jpeg";
			Process p = Runtime.getRuntime().exec(new String[] {"streamer", "-s", "640x480", "-o", tmpFile});
			p.waitFor();
			FileInputStream stream = new FileInputStream(tmpFile);
			return ImageTools.open(stream);
		} catch (Exception e) {
			Console.error(e);
			return null;
		}
	}

	// -- Load ----------------------------------------

	public static BufferedImage open(InputStream data) {
		try {
			return ImageIO.read(data);
		} catch (Exception e) {
			Console.error(e);
			return null;
		}
	}

	/** Same as open, but won't display any error message, only return null on error */
	public static BufferedImage tryOpen(InputStream data) {
		try {
			return ImageIO.read(data);
		} catch (Exception e) {
			return null;
		}
	}

	// -- Save ----------------------------------------

	public static boolean saveAs(RenderedImage image, OutputStream output, String format) {
		try {
			return ImageIO.write(image, format, output);
		} catch (Exception e) {
			Console.error(e);
			return false;
		}
	}

	public static boolean saveAs(RenderedImage image, OutputStream output) {
		return saveAs(image, output, "png");
	}

	public static byte[] toByteArray(RenderedImage image, String format) {
		ByteOutputStream output = new ByteOutputStream();
		if (saveAs(image, output, format)) {
			return output.getBytes();
		} else {
			return null;
		}
	}

	public static byte[] toJPEGByteArray(RenderedImage image) {
		return toByteArray(image, "jpeg");
	}

	public static byte[] toPNGByteArray(RenderedImage image) {
		return toByteArray(image, "png");
	}

	// -- Generate ----------------------------------------

	public static BufferedImage generateImage(int width, int height, Color color) {
		try {
			BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics2D g = img.createGraphics();
			g.setColor(color);
			g.fillRect(0, 0, width, height);
			g.dispose();
			return img;
		} catch (Exception e) {
			Console.error(e);
			return null;
		}
	}
}
